﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;

namespace YJKRevitWallModule.WallModule
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class ChangeThick : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			Transaction transaction = new Transaction(cmdData.Application.ActiveUIDocument.Document, this.ToString());
			transaction.Start();
			try
			{
				double dNewThick = 0.0;
				Wall1Filter wall1Filter = new Wall1Filter();
				Reference reference = cmdData.Application.ActiveUIDocument.Selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, wall1Filter, "请选择要改变保温层厚度的墙体：");
				Wall wall = cmdData.Application.ActiveUIDocument.Document.GetElement(reference) as Wall;
				foreach (CompoundStructureLayer compoundStructureLayer in wall.WallType.GetCompoundStructure().GetLayers())
				{
					if ((int)compoundStructureLayer.Function == 3)
					{
						dNewThick = compoundStructureLayer.Width * 304.8;
					}
				}
				IntPtr mainWindowHandle = Process.GetCurrentProcess().MainWindowHandle;
				new DlgChangeWallThick(cmdData, ref message, elements, wall)
				{
					m_dNewThick = dNewThick
                }.Show((System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle(mainWindowHandle));
				transaction.Commit();
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				transaction.Commit();
				return Result.Cancelled;
			}
			catch (Exception ex)
			{
				transaction.RollBack();
				message = ex.Message;
				return Result.Failed;
			}
			return 0;
		}
	}
}
